package gen.parser;

public class RegexValidator {

	public static boolean validate(String regex) {
		return checkDoubleBracket(regex)
				&& checkEmptyRange(regex);
	}

	private static boolean checkEmptyRange(String regex) {
		
		for (int i = 0; i < regex.length(); i++) {
			if (regex.charAt(i) == '-') {
				if (i == 0 || i == regex.length()-1)
					return false;
				else {
					char lowerChar = regex.charAt(i-1);
					char higherChar = regex.charAt(i+1);
					if (lowerChar > higherChar)
						return false;
				}
			}
		}
		
		return true;
	}

	private static boolean checkDoubleBracket(String regex) {
		boolean openBracketFound = false;
		for (int i = 0; i < regex.length(); i++) {
			char c = regex.charAt(i);
			
			if (c == '[') {
				//Check if bracket is escaped (ie: '\[')
				if (isCharEscaped(regex, i))
					continue;
				
				if (!openBracketFound)
					openBracketFound = true;
				else
					return false;
			}
			else if (c == ']') {
				if (openBracketFound)
					openBracketFound = false;
				else {
					if (!isCharEscaped(regex, i))
						return false;
				}
			}
		}
		return true;
	}
	
	private static boolean isCharEscaped(String str, int pos) {
		if (pos == 0)
			return false;
		else if (pos == 1 && str.charAt(0) == '\\')
			return true;
		else {
			int numBrackets = 0;
			for (int i = pos-1; i >= 0; i--) {
				char c = str.charAt(i);
				if (c == '\\')
					numBrackets++;
				else
					break;
			}
			
			if (numBrackets % 2 == 0)
				return false;
			else
				return true;
		}
	}
}
